import pyautogui
import time
import threading
from pynput import keyboard
from collections import defaultdict
import tkinter as tk
from tkinter import ttk, messagebox
import queue
import json
import logging
from pathlib import Path
from threading import Lock

class ConfigurationManager:
    """配置管理器，负责读取和保存应用配置"""
    def __init__(self, config_file="mouse_click_simulator_config.json"):
        self.config_file = Path(config_file)
        self.default_config = {
            "use_default": True,
            "click_count": 0,
            "click_interval": 1.0,
            "delay_before_first_click": 3.0
        }
        self.config = self.load_config()
    
    def load_config(self):
        """加载配置文件"""
        try:
            if self.config_file.exists():
                with open(self.config_file, 'r', encoding='utf-8') as f:
                    config = json.load(f)
                    # 确保配置包含所有必要的键
                    for key in self.default_config:
                        if key not in config:
                            config[key] = self.default_config[key]
                    return config
            return self.default_config.copy()
        except Exception as e:
            logging.error(f"加载配置文件失败: {e}")
            return self.default_config.copy()
    
    def save_config(self):
        """保存配置文件"""
        try:
            with open(self.config_file, 'w', encoding='utf-8') as f:
                json.dump(self.config, f, indent=4)
        except Exception as e:
            logging.error(f"保存配置文件失败: {e}")
    
    def get(self, key, default=None):
        """获取配置值"""
        return self.config.get(key, default)
    
    def set(self, key, value):
        """设置配置值"""
        self.config[key] = value
        self.save_config()

class ClickTimerApp:
    """美化版点击倒计时应用"""
    def __init__(self, parent, config_manager):
        self.parent = parent
        self.parent.title("鼠标点击模拟器")
        self.parent.attributes('-topmost', True)
        self.parent.resizable(False, False)
        self.parent.configure(bg="#1E1E1E")
        
        self.config_manager = config_manager
        
        # 设置中文字体支持
        self.font_family = ("SimHei", "Microsoft YaHei", "Arial")
        
        # 数据
        self.reset_data()
        
        # 创建UI
        self.create_widgets()
        
        # 启动倒计时
        self.update_countdown()
    
    def reset_data(self):
        """重置数据到配置值"""
        self.delay_seconds = self.config_manager.get("delay_before_first_click", 3.0)
        self.interval_seconds = self.config_manager.get("click_interval", 1.0)
        self.is_limited = self.config_manager.get("click_count", 0) > 0
        self.total_clicks = self.config_manager.get("click_count", 0)
        self.current_click = 0
        self.time_remaining = self.delay_seconds
        self.state = "DELAY"
    
    def create_widgets(self):
        """创建UI组件"""
        # 主框架
        main_frame = tk.Frame(self.parent, bg="#1E1E1E")
        main_frame.pack(padx=20, pady=20, fill=tk.BOTH, expand=True)
        
        # 标题
        title_label = tk.Label(
            main_frame, 
            text="鼠标点击模拟器", 
            font=(self.font_family[0], 16, "bold"),
            bg="#1E1E1E",
            fg="#FFFFFF"
        )
        title_label.pack(pady=(0, 15))
        
        # 倒计时显示
        self.countdown_var = tk.StringVar(value=f"准备开始: {self.time_remaining:.1f}秒")
        self.countdown_label = tk.Label(
            main_frame, 
            textvariable=self.countdown_var, 
            font=(self.font_family[0], 36, "bold"),
            bg="#1E1E1E",
            fg="#4CAF50"
        )
        self.countdown_label.pack(pady=10)
        
        # 点击进度
        self.progress_var = tk.StringVar(value="")
        self.progress_label = tk.Label(
            main_frame, 
            textvariable=self.progress_var, 
            font=(self.font_family[0], 12),
            bg="#1E1E1E",
            fg="#FFFFFF"
        )
        self.progress_label.pack(pady=5)
        
        # 进度条
        self.progress_bar = ttk.Progressbar(
            main_frame, 
            orient="horizontal",
            length=300,
            mode="determinate"
        )
        self.progress_bar.pack(pady=10)
        
        # 状态指示
        self.status_var = tk.StringVar(value="等待开始")
        self.status_label = tk.Label(
            main_frame, 
            textvariable=self.status_var, 
            font=(self.font_family[0], 12),
            bg="#1E1E1E",
            fg="#FFC107"
        )
        self.status_label.pack(pady=5)
        
        # 配置信息
        config_frame = tk.Frame(main_frame, bg="#1E1E1E")
        config_frame.pack(pady=10)
        
        self.config_var = tk.StringVar()
        use_default = self.config_manager.get("use_default", True)
        click_count = self.config_manager.get("click_count", 0)
        interval = self.config_manager.get("click_interval", 1.0)
        delay = self.config_manager.get("delay_before_first_click", 3.0)
        
        config_text = "使用默认设置" if use_default else f"手动设置: {click_count}次点击，间隔{interval}秒，延迟{delay}秒"
        self.config_var.set(config_text)
        
        config_label = tk.Label(
            config_frame, 
            textvariable=self.config_var, 
            font=(self.font_family[0], 10),
            bg="#1E1E1E",
            fg="#AAAAAA"
        )
        config_label.pack()
        
        # 底部信息
        info_label = tk.Label(
            main_frame, 
            text="按 Ctrl+Alt+C 停止 | ESC 退出程序 | Ctrl+Alt+S 设置", 
            font=(self.font_family[0], 10),
            bg="#1E1E1E",
            fg="#888888"
        )
        info_label.pack(side=tk.BOTTOM, pady=10)
        
        # 设置进度条样式
        self.style = ttk.Style()
        self.style.theme_use('clam')
        self.style.configure("green.Horizontal.TProgressbar", 
                            background="#4CAF50", 
                            troughcolor="#303030",
                            borderwidth=0)
        self.progress_bar.configure(style="green.Horizontal.TProgressbar")
        
        # 初始化进度条
        if self.is_limited:
            self.progress_bar["maximum"] = self.total_clicks
            self.progress_bar["value"] = 0
            self.update_progress()
    
    def update_progress(self):
        """更新进度显示"""
        if self.is_limited:
            self.progress_var.set(f"点击次数: {self.current_click}/{self.total_clicks}")
            self.progress_bar["value"] = self.current_click
        else:
            self.progress_var.set(f"点击次数: {self.current_click}")
    
    def update_countdown(self):
        """更新倒计时显示"""
        if self.state == "DELAY":
            self.countdown_var.set(f"准备开始: {self.time_remaining:.1f}秒")
            self.time_remaining -= 0.1
            if self.time_remaining <= 0:
                self.state = "CLICKING"
                self.time_remaining = self.interval_seconds
                self.countdown_var.set(f"下一次点击: {self.time_remaining:.1f}秒")
                self.status_var.set("正在点击")
                self.update_progress()
            else:
                self.parent.after(100, self.update_countdown)
        elif self.state == "CLICKING":
            self.countdown_var.set(f"下一次点击: {self.time_remaining:.1f}秒")
            self.time_remaining -= 0.1
            if self.time_remaining <= 0:
                self.time_remaining = self.interval_seconds
                self.update_progress()
                if self.is_limited and self.current_click >= self.total_clicks:
                    self.state = "PAUSED"
                    self.countdown_var.set("点击完成!")
                    self.status_var.set("已完成所有点击")
                    self.progress_bar.configure(style="green.Horizontal.TProgressbar")
                else:
                    self.parent.after(100, self.update_countdown)
            else:
                self.parent.after(100, self.update_countdown)
        elif self.state == "PAUSED":
            pass
    
    def set_state(self, state):
        """设置应用状态"""
        self.state = state
        if state == "DELAY":
            self.reset_data()
            # 更新配置显示
            use_default = self.config_manager.get("use_default", True)
            click_count = self.config_manager.get("click_count", 0)
            interval = self.config_manager.get("click_interval", 1.0)
            delay = self.config_manager.get("delay_before_first_click", 3.0)
            config_text = "使用默认设置" if use_default else f"手动设置: {click_count}次点击，间隔{interval}秒，延迟{delay}秒"
            self.config_var.set(config_text)
            
            self.countdown_var.set(f"准备开始: {self.time_remaining:.1f}秒")
            self.status_var.set("等待开始")
            self.parent.after(100, self.update_countdown)
        elif state == "PAUSED":
            self.status_var.set("已暂停")
            self.countdown_var.set("已暂停")
            self.progress_bar.configure(style="Horizontal.TProgressbar")
        elif state == "CLICKING":
            self.status_var.set("正在点击")
            if self.state != "CLICKING":
                self.parent.after(100, self.update_countdown)
    
    def update_config(self):
        """从配置管理器更新配置"""
        self.delay_seconds = self.config_manager.get("delay_before_first_click", 3.0)
        self.interval_seconds = self.config_manager.get("click_interval", 1.0)
        self.is_limited = self.config_manager.get("click_count", 0) > 0
        self.total_clicks = self.config_manager.get("click_count", 0)

class KeyboardManager:
    """键盘管理类，处理热键监听"""
    def __init__(self, toggle_callback, settings_callback, exit_callback):
        self.toggle_hotkey = {
            keyboard.Key.ctrl_l,
            keyboard.Key.alt_l,
            keyboard.KeyCode(char='c')
        }
        self.settings_hotkey = {
            keyboard.Key.ctrl_l,
            keyboard.Key.alt_l,
            keyboard.KeyCode(char='s')
        }
        self.key_timestamps = defaultdict(float)
        self.hotkey_window = 1.0
        self.current_keys = set()
        
        self.toggle_callback = toggle_callback
        self.settings_callback = settings_callback
        self.exit_callback = exit_callback
        
        self.listener = keyboard.Listener(on_press=self.on_press, on_release=self.on_release)
        self.listener.start()
    
    def on_press(self, key):
        """处理按键按下事件"""
        # 特殊处理：将C键的虚拟键码(67)转换为字符键
        processed_key = key
        if isinstance(key, keyboard.KeyCode) and key.vk == 67:
            processed_key = keyboard.KeyCode(char='c')
        elif isinstance(key, keyboard.KeyCode) and key.vk == 83:  # S键
            processed_key = keyboard.KeyCode(char='s')
            
        self.key_timestamps[processed_key] = time.time()
        self.current_keys.add(processed_key)
        
        # 检查主热键
        if self.toggle_hotkey.issubset(self.current_keys):
            print("[热键] 触发点击切换")
            self.toggle_callback()
            return
            
        # 检查设置热键
        if self.settings_hotkey.issubset(self.current_keys):
            print("[热键] 触发设置菜单")
            self.settings_callback()
            self.current_keys.clear()  # 防止重复触发
    
    def on_release(self, key):
        """处理按键释放事件"""
        # 特殊处理：将C键的虚拟键码转换为字符键
        if isinstance(key, keyboard.KeyCode) and key.vk == 67:
            key = keyboard.KeyCode(char='c')
        elif isinstance(key, keyboard.KeyCode) and key.vk == 83:  # S键
            key = keyboard.KeyCode(char='s')
            
        if key in self.current_keys:
            self.current_keys.remove(key)
            
        if key == keyboard.Key.esc:
            print("[系统] 检测到ESC键，准备退出...")
            self.exit_callback()
            return False
    
    def stop(self):
        """停止键盘监听"""
        self.listener.stop()
        self.listener.join()

class MouseClickSimulator:
    """鼠标点击模拟器主类"""
    def __init__(self):
        self.config_manager = ConfigurationManager()
        self.setup_logging()
        
        self.is_clicking = False
        self.current_clicks = 0
        self.click_thread = None
        self.root = None
        self.click_app = None
        self.command_queue = queue.Queue()
        self.is_running = True
        self.keyboard_manager = None
        self.click_lock = Lock()  # 用于线程安全的点击计数
        
        logging.info("鼠标点击模拟器初始化完成")
    
    def setup_logging(self):
        """设置日志记录"""
        logging.basicConfig(
            level=logging.INFO,
            format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
            filename='mouse_click_simulator.log'
        )
    
    def create_gui(self):
        """创建GUI界面"""
        if self.root is None:
            self.root = tk.Tk()
            self.root.withdraw()  # 初始隐藏主窗口
            self.root.protocol("WM_DELETE_WINDOW", self.on_close_window)
            self.process_commands()
    
    def process_commands(self):
        """处理来自其他线程的命令"""
        try:
            while not self.command_queue.empty():
                command, *args = self.command_queue.get()
                if command == "show_window":
                    self._show_window()
                elif command == "set_state":
                    self._set_state(*args)
                elif command == "reset":
                    self._reset()
                elif command == "close":
                    self._close()
                elif command == "update_click_count":
                    click_count = args[0]
                    if self.click_app:
                        self.click_app.current_click = click_count
                        self.click_app.update_progress()
        except Exception as e:
            logging.error(f"处理命令时出错: {e}")
        if self.root and self.is_running:
            self.root.after(100, self.process_commands)
    
    def on_close_window(self):
        """处理窗口关闭事件"""
        logging.info("窗口已隐藏")
        print("[系统] 窗口已隐藏，不影响点击功能运行")
        if self.root:
            self.root.withdraw()  # 隐藏窗口而不是销毁
    
    def show_countdown_window(self):
        """显示倒计时窗口（线程安全）"""
        self.command_queue.put(("show_window",))
    
    def _show_window(self):
        """实际显示窗口的方法（在主线程执行）"""
        self.create_gui()
        if self.click_app:
            self._reset()
        else:
            self.click_app = ClickTimerApp(self.root, self.config_manager)
        self.root.deiconify()
    
    def set_click_settings(self):
        """设置点击参数"""
        print("\n=== 设置点击参数 ===")
        
        # 获取当前配置值
        current_use_default = self.config_manager.get("use_default", True)
        current_click_count = self.config_manager.get("click_count", 0)
        current_click_interval = self.config_manager.get("click_interval", 1.0)
        current_delay = self.config_manager.get("delay_before_first_click", 3.0)
        
        # 创建设置窗口
        settings_window = tk.Toplevel(self.root)
        settings_window.title("设置点击参数")
        settings_window.geometry("350x280")  # 适当增大窗口高度
        settings_window.resizable(False, False)
        settings_window.configure(bg="#1E1E1E")
        settings_window.transient(self.root)  # 设置为主窗口的子窗口
        settings_window.grab_set()  # 模态窗口
        
        # 设置中文字体支持
        font_family = ("SimHei", "Microsoft YaHei", "Arial")
        
        # 主框架
        main_frame = tk.Frame(settings_window, bg="#1E1E1E")
        main_frame.pack(padx=20, pady=20, fill=tk.BOTH, expand=True)
        
        # 是否使用默认设置
        use_default_var = tk.BooleanVar(value=current_use_default)
        
        default_frame = tk.Frame(main_frame, bg="#1E1E1E")
        default_frame.pack(fill=tk.X, pady=5)
        
        default_check = tk.Checkbutton(
            default_frame,
            text="使用默认设置",
            variable=use_default_var,
            bg="#1E1E1E",
            fg="#FFFFFF",
            font=(font_family[0], 10),
            command=lambda: self.toggle_settings(use_default_var, [count_entry, interval_entry, delay_entry])
        )
        default_check.pack(anchor=tk.W)
        
        # 设置选项框架
        settings_frame = tk.Frame(main_frame, bg="#1E1E1E")
        settings_frame.pack(fill=tk.BOTH, expand=True, pady=10)
        
        # 点击次数
        count_frame = tk.Frame(settings_frame, bg="#1E1E1E")
        count_frame.pack(fill=tk.X, pady=5)
        
        count_label = tk.Label(
            count_frame,
            text="点击次数:",
            bg="#1E1E1E",
            fg="#FFFFFF",
            font=(font_family[0], 10)
        )
        count_label.pack(side=tk.LEFT, padx=5)
        
        count_var = tk.StringVar(value=str(current_click_count))
        count_entry = tk.Entry(
            count_frame,
            textvariable=count_var,
            font=(font_family[0], 10),
            width=10
        )
        count_entry.pack(side=tk.LEFT)
        
        count_info = tk.Label(
            count_frame,
            text="(0表示无限次)",
            bg="#1E1E1E",
            fg="#AAAAAA",
            font=(font_family[0], 8)
        )
        count_info.pack(side=tk.LEFT, padx=5)
        
        # 点击间隔
        interval_frame = tk.Frame(settings_frame, bg="#1E1E1E")
        interval_frame.pack(fill=tk.X, pady=5)
        
        interval_label = tk.Label(
            interval_frame,
            text="点击间隔(秒):",
            bg="#1E1E1E",
            fg="#FFFFFF",
            font=(font_family[0], 10)
        )
        interval_label.pack(side=tk.LEFT, padx=5)
        
        interval_var = tk.StringVar(value=str(current_click_interval))
        interval_entry = tk.Entry(
            interval_frame,
            textvariable=interval_var,
            font=(font_family[0], 10),
            width=10
        )
        interval_entry.pack(side=tk.LEFT)
        
        # 首次点击延迟
        delay_frame = tk.Frame(settings_frame, bg="#1E1E1E")
        delay_frame.pack(fill=tk.X, pady=5)
        
        delay_label = tk.Label(
            delay_frame,
            text="首次点击延迟(秒):",
            bg="#1E1E1E",
            fg="#FFFFFF",
            font=(font_family[0], 10)
        )
        delay_label.pack(side=tk.LEFT, padx=5)
        
        delay_var = tk.StringVar(value=str(current_delay))
        delay_entry = tk.Entry(
            delay_frame,
            textvariable=delay_var,
            font=(font_family[0], 10),
            width=10
        )
        delay_entry.pack(side=tk.LEFT)
        
        # 按钮框架
        button_frame = tk.Frame(main_frame, bg="#1E1E1E")
        button_frame.pack(side=tk.BOTTOM, fill=tk.X, pady=10)
        
        # 保存按钮
        def save_settings():
            try:
                use_default = use_default_var.get()
                self.config_manager.set("use_default", use_default)
                
                if not use_default:
                    click_count = int(count_var.get())
                    click_interval = float(interval_var.get())
                    delay = float(delay_var.get())
                    
                    # 验证输入
                    if click_count < 0:
                        raise ValueError("点击次数不能为负数")
                    if click_interval <= 0:
                        raise ValueError("点击间隔必须大于0")
                    if delay < 0:
                        raise ValueError("延迟时间不能为负数")
                    
                    self.config_manager.set("click_count", click_count)
                    self.config_manager.set("click_interval", click_interval)
                    self.config_manager.set("delay_before_first_click", delay)
                
                status = "默认设置" if use_default else f"{click_count}次点击，间隔{click_interval}秒，延迟{delay}秒"
                print(f"✅ 设置成功: {status}")
                messagebox.showinfo("成功", f"设置成功: {status}")
                
                if self.click_app:
                    self.command_queue.put(("reset",))
                
                settings_window.destroy()
            except ValueError as e:
                logging.error(f"设置参数失败: {e}")
                messagebox.showerror("错误", f"设置失败: {e}")
            except Exception as e:
                logging.error(f"保存设置时出错: {e}")
                messagebox.showerror("错误", f"保存设置时出错: {e}")
        
        save_button = tk.Button(
            button_frame,
            text="保存设置",
            command=save_settings,
            bg="#4CAF50",
            fg="#FFFFFF",
            font=(font_family[0], 10),
            padx=10,
            pady=5
        )
        save_button.pack(side=tk.RIGHT)
        
        # 取消按钮
        cancel_button = tk.Button(
            button_frame,
            text="取消",
            command=settings_window.destroy,
            bg="#607D8B",
            fg="#FFFFFF",
            font=(font_family[0], 10),
            padx=10,
            pady=5
        )
        cancel_button.pack(side=tk.RIGHT, padx=10)
        
        # 初始设置
        self.toggle_settings(use_default_var, [count_entry, interval_entry, delay_entry])
        
        # 确保窗口显示
        settings_window.update_idletasks()
        settings_window.deiconify()
        settings_window.focus_set()
    
    def toggle_settings(self, use_default_var, entry_widgets):
        """根据是否使用默认设置来启用或禁用设置选项"""
        state = tk.DISABLED if use_default_var.get() else tk.NORMAL
        for widget in entry_widgets:
            widget.configure(state=state)
    
    def _reset(self):
        """重置GUI（在主线程执行）"""
        if self.click_app:
            self.click_app.update_config()
            self.click_app.reset_data()
    
    def start_clicking(self):
        """开始模拟鼠标点击"""
        with self.click_lock:  # 线程安全
            self.current_clicks = 0
            
        # 使用默认设置
        use_default = self.config_manager.get("use_default", True)
        
        if use_default:
            click_count = self.config_manager.get("click_count", 0)
            interval = self.config_manager.get("click_interval", 1.0)
            delay = self.config_manager.get("delay_before_first_click", 3.0)
        else:
            # 如果不使用默认设置，则使用上次保存的手动设置
            click_count = self.config_manager.get("click_count", 0)
            interval = self.config_manager.get("click_interval", 1.0)
            delay = self.config_manager.get("delay_before_first_click", 3.0)
        
        logging.info(f"开始模拟鼠标点击: {'无限次' if click_count == 0 else f'{click_count}次'}，间隔{interval}秒，延迟{delay}秒")
        print(f"✅ 准备开始模拟鼠标点击: "
              f"{'无限次' if click_count == 0 else f'{click_count}次'}，"
              f"间隔{interval}秒，延迟{delay}秒")
        
        self.show_countdown_window()
        
        # 精确倒计时实现
        start_time = time.time()
        end_time = start_time + delay
        
        while time.time() < end_time and self.is_clicking and self.is_running:
            remaining = end_time - time.time()
            time.sleep(0.1)
        
        if not self.is_clicking or not self.is_running:
            return
            
        logging.info("开始执行点击")
        print("💥 开始执行点击")
        
        self.command_queue.put(("set_state", "CLICKING"))
        
        try:
            while self.is_clicking and self.is_running:
                pyautogui.click()
                
                with self.click_lock:  # 线程安全
                    self.current_clicks += 1
                    self.command_queue.put(("update_click_count", self.current_clicks))
                
                # 精确控制点击间隔
                click_time = time.time()
                next_click_time = click_time + interval
                
                # 检查是否达到点击次数限制
                with self.click_lock:  # 线程安全
                    if click_count > 0 and self.current_clicks >= click_count:
                        logging.info(f"已完成{click_count}次点击")
                        print(f"✅ 已完成{click_count}次点击")
                        self.is_clicking = False
                        self.command_queue.put(("set_state", "PAUSED"))
                        self.close_window_if_running()
                        break
                
                # 等待直到下一次点击时间
                while time.time() < next_click_time and self.is_clicking and self.is_running:
                    time.sleep(0.01)  # 小睡一会儿，避免CPU占用过高
                    
        except Exception as e:
            logging.error(f"点击过程中出错: {e}")
            print(f"点击过程中出错: {e}")
            self.is_clicking = False
            self.command_queue.put(("set_state", "PAUSED"))
            self.close_window_if_running()
        finally:
            logging.info("鼠标点击模拟已停止")
            print("❌ 鼠标点击模拟已停止")
            if self.is_clicking and self.click_app:
                self.command_queue.put(("set_state", "PAUSED"))
                self.close_window_if_running()
    
    def close_window_if_running(self):
        """如果程序仍在运行，关闭窗口"""
        if self.click_app and self.is_running:
            self.command_queue.put(("close",))
    
    def _set_state(self, state):
        """设置GUI状态（在主线程执行）"""
        if self.click_app:
            self.click_app.set_state(state)
    
    def toggle_clicking(self):
        """切换点击状态"""
        if not self.is_running:
            return
            
        prev_state = self.is_clicking
        self.is_clicking = not prev_state
        logging.info(f"点击状态已切换: {'启动' if self.is_clicking else '停止'}")
        print(f"[状态] 点击状态已切换: {'启动' if self.is_clicking else '停止'}")
        
        if self.is_clicking:
            logging.info("创建并启动点击线程")
            print("[线程] 创建并启动点击线程")
            self.click_thread = threading.Thread(target=self.start_clicking)
            self.click_thread.daemon = True
            self.click_thread.start()
        else:
            logging.info("请求停止点击线程")
            print("[线程] 请求停止点击线程")
            if self.click_thread and self.click_thread.is_alive():
                self.is_clicking = False
                self.click_thread.join(timeout=1.0)
                if self.click_thread.is_alive():
                    logging.warning("点击线程未能及时停止")
                    print("[警告] 点击线程未能及时停止")
                else:
                    logging.info("点击线程已停止")
                    print("[线程] 点击线程已停止")
            if self.click_app:
                self.command_queue.put(("set_state", "PAUSED"))
                self.close_window_if_running()
    
    def run(self):
        """运行模拟器"""
        logging.info("启动鼠标点击模拟器")
        print("\n=== 鼠标点击模拟器 ===")
        print(f"主热键: Ctrl_L + Alt_L + C (切换点击状态)")
        print(f"设置热键: Ctrl_L + Alt_L + S (设置点击参数)")
        print("按ESC键退出")
        
        # 加载配置
        use_default = self.config_manager.get("use_default", True)
        click_count = self.config_manager.get("click_count", 0)
        interval = self.config_manager.get("click_interval", 1.0)
        delay = self.config_manager.get("delay_before_first_click", 3.0)
        
        if use_default:
            print(f"\n当前配置: 使用默认设置")
        else:
            print(f"\n当前配置: {click_count}次点击，间隔{interval}秒，延迟{delay}秒")
        
        # 设置键盘管理
        self.keyboard_manager = KeyboardManager(
            self.toggle_clicking,
            self.set_click_settings,
            self.stop
        )
        
        # 启动GUI
        self.create_gui()
        self.root.mainloop()
        
        # 清理资源
        self.stop()
    
    def stop(self):
        """停止模拟器"""
        if not self.is_running:
            return
            
        logging.info("准备停止模拟器")
        print("[系统] 准备停止模拟器...")
        
        self.is_running = False
        self.is_clicking = False
        
        # 停止键盘监听
        if self.keyboard_manager:
            self.keyboard_manager.stop()
        
        # 等待点击线程结束
        if self.click_thread and self.click_thread.is_alive():
            self.click_thread.join(timeout=1.0)
            if self.click_thread.is_alive():
                logging.warning("点击线程未能及时停止")
                print("[警告] 点击线程未能及时停止")
        
        # 关闭GUI
        if self.root:
            self.command_queue.put(("close",))
            time.sleep(0.2)
            
        logging.info("程序已退出")
        print("[系统] 程序已退出")

if __name__ == "__main__":
    print("[主程序] 启动鼠标点击模拟器...")
    simulator = MouseClickSimulator()
    simulator.run()